package com.shipwe.loans.ui.presenter

import com.shipwe.loans.analyse.util.GoogleShipweUtil
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipwePresenter
import com.shipwe.loans.ui.view.IUserLoginView
import com.shipwe.loans.utils.ShipweDateUtil
import com.shipwe.loans.utils.helper.ShipweAppAnalysisHelper
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.helper.TestAnalysisAddEvent
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/28 11:59
 * @Annotation：登录
 */
class UserLoginPresenter(private val iView: IUserLoginView): ShipwePresenter(iView) {

    /**
     * 登录
     */
    fun requestUserLoginAction(){
        //登录之前，需要验证手机号是否在 app配置 accList里存在
        val accItem = checkUserLoginConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_IS_CONFIG_ACCOUNT,true)
            onUserLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",ApiService.API_PATH.SHIPWE_API_LOGIN_NO_CODE_PATH)
                put("mobile",iView.getUserLoginMobile())//手机号
                put("code","0000")//验证码
                put("channelCode", GoogleShipweUtil.getInstallReferrer())//渠道号
                put("subChannelCode", GoogleShipweUtil.getInstallReferrer())//子渠道号
                put("directLoginFlag","YES")//是否直接登录
                put("notBindWalletFlag","YES")//不自动绑卡
                put("loginParam","")//验证码接口返回的参数
            }

        doHttpPostAction(httpUrl, params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId")
                    val userToken = obj.optString("token")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    if ("YES" == isAdSource){
                        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_IS_ADSOURCE,true)
                    }

                    //登录类型 == 注册，需要打点
                    if (type == "REGISTER"){
                        TestAnalysisAddEvent.addRegisterEvent()
                    }
                    onUserLoginSuccess(userId,userToken)
                }
            }

            override fun onRequestError(error: JSONObject) {
                if (error.optString("code") == "9999"){
                    iView.showUserLoginFailure(error)
                }
            }

            override fun onRequestFinish() {
                iView.dismissShipweLoading()
            }
        })
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUserLoginConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val customize = CustomConfigsHelper.getShipweConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (iView.getUserLoginMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录成功
     */
    private fun onUserLoginSuccess(uid: String, token: String){
        iView.dismissShipweLoading()
        //保存手机号码，个人中心使用
        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_MOBILE, iView.getUserLoginMobile())
        //保存用户登录时间
        val loginTime = ShipweDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_LOGIN,true)
        //保存用户id
        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_USERID,uid)
        //保存用户Token
        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        ShipweAppAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入主页
        iView.showUserLoginMainPage()
    }
}